package network

import (
	"bytes"
	"net"
)

const (
	BUFF_SIZE = 512
)

type OnReceiver func(*TcpClient,[]byte)
type OnError func(*TcpClient,error)

type TcpClient struct {
	conn net.Conn
	receiver OnReceiver
	err OnError
	ID string
}

func (c *TcpClient) SetHandlers(receiver OnReceiver,err OnError) {
	c.receiver = receiver
	c.err = err
}

func (c *TcpClient) Write(data []byte) error {
	_,err := c.conn.Write(data)
	return err
}

func (c *TcpClient) Close() {
	c.conn.Close()
}

func (c *TcpClient) start() {
	go func() {
		buf := make([]byte,BUFF_SIZE)
		reader := bytes.NewBuffer(make([]byte,BUFF_SIZE))
		reader.Reset()

		for {
			size,err := c.conn.Read(buf)
			if err != nil {
				if c.err != nil {
					c.err(c,err)
				}
				return
			}

			if size > 0 {
				reader.Write(buf[:size])
				if size >= BUFF_SIZE {
					continue
				}
			}

			data := reader.Bytes()
			if c.receiver != nil {
				c.receiver(c,data)
			}
			reader.Reset()
		}
	}()
}

func NewClient(conn net.Conn) *TcpClient {
	client := &TcpClient{conn: conn}
	return client
}


